<template>
  <div class="login-page">
    <el-card class="login-card">
      <div class="card-header">
        <h2 class="title">个人注册</h2>
      </div>
      <!-- 用户类型选择 -->
      <div class="user-type">
        <el-button
          type="primary"
          :class="{ active: userType === 'recruiter' }"
          @click="toggleUserType('recruiter')"
          plain
          class="recruiter-btn"
        >
          我要招聘
        </el-button>
        <el-button
          type="primary"
          :class="{ active: userType === 'seeker' }"
          @click="toggleUserType('seeker')"
          plain
          class="seeker-btn"
        >
          我要求职
        </el-button>
      </div>
      <!-- 注册表单 -->
      <el-form :model="form" :rules="rules" ref="loginForm" label-width="0">
        <el-form-item prop="phone">
          <el-input
            prefix-icon="el-icon-phone"
            v-model="form.phone"
            type="tel"
            placeholder="请输入手机号"
            pattern="[0-9]{11}"
            :maxlength="11"
          >
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            prefix-icon=" el-icon-lock"
            v-model="form.password"
            :type="passwordType"
            placeholder="请输入密码"
            show-password
          >
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            prefix-icon=" el-icon-lock"
            v-model="form.confirmPassword"
            :type="confirmPasswordType"
            placeholder="请再次输入密码"
            show-password
          >
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleRegister"
            :loading="isLoading"
            style="width: 100%"
          >
            立即注册
          </el-button>
        </el-form-item>
        <!-- 注册链接 -->
        <div class="link-group">
          <!-- 登录页面中的注册链接 -->
          <el-button @click="goLogin" class="register"
            >已有账号，返回登录</el-button
          >
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { registerBySeeker, registerByRecruiter } from "@/api/login";
import { Message } from "element-ui";

export default {
  data() {
    return {
      userType: "seeker",
      form: {
        phone: "",
        password: "",
        confirmPassword: "",
      },
      passwordVisible: false,
      confirmPasswordVisible: false,
      isLoading: false,
      rules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入有效手机号",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 4,
            max: 20,
            message: "密码长度在4-20位之间",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value !== this.form.password) {
                callback(new Error("两次输入的密码不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },

  computed: {
    passwordType() {
      return this.passwordVisible ? "text" : "password";
    },
    confirmPasswordType() {
      return this.confirmPasswordVisible ? "text" : "password";
    },
    isValidPhone() {
      return /^1[3-9]\d{9}$/.test(this.form.phone);
    },
  },

  created() {
    // 从路由参数中获取 userType
    const userType = this.$route.query.userType;
    if (userType === "recruiter" || userType === "seeker") {
      this.userType = userType;
    }
  },

  methods: {
    toggleUserType(type) {
      this.userType = type;
    },
    goLogin() {
      this.$router.push({
        path: "/login",
        query: { userType: this.userType },
      });
    },

    // 注册
    async handleRegister() {
      this.$refs.loginForm.validate(async (valid) => {
        if (!valid) return;
        try {
          this.isLoading = true;
          const { phone, password } = this.form;
          if (this.userType === "recruiter") {
            const response = await registerByRecruiter({ phone, password });
            const { code, msg } = response.data;
            if (code === 201) {
              Message.success("招聘者注册成功");
              this.$router.push("/login");
            } else {
              Message.error(msg || "招聘者注册失败");
            }
          } else {
            const response = await registerBySeeker({ phone, password });
            console.log("求职者注册接口返回:", response);
            const { code, msg } = response.data;
            if (code === 201) {
              Message.success("求职者注册成功");
              this.$router.push("/login");
            } else {
              Message.error(msg || "求职者注册失败");
            }
          }
        } catch (error) {
          if (error.response) {
            const { status, data } = error.response;

            if (status === 422) {
              Message.error(data.msg || "该账号已注册过");
            } else {
              // 其他状态码的错误处理
              Message.error(data.msg || `网络错误: ${status}`);
            }
          } else {
            // 处理网络连接问题（如超时、断网）
            Message.error("网络请求失败，请检查网络连接");
          }
        } finally {
          this.isLoading = false;
        }
      });
    },
  },
};
</script>

<style scoped>
@import "element-ui/lib/theme-chalk/index.css";
.card-header {
  position: relative;
  margin-bottom: 30px;
  text-align: center;
}

.title {
  margin: 0;
  padding: 5px 0;
  font-size: 24px;
  color: #409eff;
}

.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  /* 背景图片路径（根据实际存放位置调整） */
  background-image: url(../../../public/image/登录页面背景.png);
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-color: #f0f2f5;
}

.login-card {
  padding: 30px 40px;
  width: 400px;
  background-color: rgba(255, 255, 255, 0.3);
}

.user-type {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  gap: 15px;
}

/* 用户类型按钮样式 */
.user-type .el-button {
  flex: 1;
  padding: 12px 0;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
  min-width: 140px;
  border: 1px solid #e4e7ed;
}

.user-type .el-button.active {
  background-color: #409eff;
  color: white;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  border-color: #409eff;
}

.captcha-container {
  display: flex;
  gap: 10px;
}

.link-group {
  margin-top: 25px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.el-input__inner {
  height: 48px;
  font-size: 16px;
}

.el-button--primary {
  height: 50px;
  font-size: 16px;
  border-radius: 8px;
}

.register {
  border: none;
  background-color: transparent;
}

.register:hover,
.register:active {
  background-color: transparent !important;
}
</style>